package com.gjzhao.fmmall.utils;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.MapUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: Excel 导入导出工具类
 * TODO 封装导入方法
 * @Author: gjzhao
 * @Date Created in 2022-01-09 2:59 下午
 */
public class EasyExcelUtil {

    /**
     * 导出 Excel
     *
     * @param response    响应
     * @param clazz       对象类型
     * @param excelType   excel类型
     * @param rawFileName excel文件名字
     * @param sheetName   sheet名字
     * @param data        数据源
     * @throws IOException
     */
    public static void exportExcel(HttpServletResponse response,
                                   Class<?> clazz,
                                   ExcelTypeEnum excelType,
                                   String rawFileName,
                                   String sheetName,
                                   Collection<?> data) throws IOException {

        setExcelRespProp(response, rawFileName);

        EasyExcel.write(response.getOutputStream())
                 .head(clazz)
                 .excelType(excelType)
                 .sheet(sheetName)
                 .doWrite(data);
    }


    /**
     * 如果导出失败，重置response，封装失败结果及失败原因
     *
     * @param response
     * @param e
     * @throws IOException
     */
    public static void exportFail(HttpServletResponse response, Exception e) throws IOException {

        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        Map<String, String> map = MapUtils.newHashMap();
        map.put("status", "failure");
        map.put("message", "下载文件失败，错误原因：" + e.getMessage());

        response.getWriter().println(JSONUtil.toJsonStr(map));
    }


    /**
     * 设置excel下载响应头属性
     *
     * @param response    响应
     * @param rawFileName 导出excel名字
     * @throws UnsupportedEncodingException
     */
    private static void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //URLEncoder.encode 用以防止中文乱码
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

}
